package com.centaline.androidsalesblog.fragments.list;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.sale.RentDetailActivity;
import com.centaline.androidsalesblog.activities.sale.SaleDetailActivity;
import com.centaline.androidsalesblog.adapter.PostNewsAdapter;
import com.centaline.androidsalesblog.api.sale.PostListApi;
import com.centaline.androidsalesblog.api.usercenter.CollectInfoChangeApi;
import com.centaline.androidsalesblog.api.usercenter.UpdateCollectIsRead;
import com.centaline.androidsalesblog.base.BaseFragment;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.model.businissobject.CollectInfoBo;
import com.centaline.androidsalesblog.model.businissobject.CollectInfoChangeBo;
import com.centaline.androidsalesblog.model.databaseobject.PostDo;
import com.centaline.androidsalesblog.model.responseobject.CollectInfoChangeRo;
import com.centaline.androidsalesblog.model.responseobject.PostListRo;
import com.centaline.androidsalesblog.model.responseobject.SimpleUserCenterRo;
import com.centaline.androidsalesblog.widgets.MRecyclerView;
import com.centanet.framework.interfaces.IRecycleViewListener;
import com.centanet.framework.interfaces.IResponseListener;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * 房源动态
 * Created by guilin on 16/3/30.
 */
public class PostNewsFragment extends BaseFragment {

    private MRecyclerView mRecyclerView;
    private boolean isRequest;

    private ArrayList<CollectInfoChangeBo> collectInfoChangeBos = new ArrayList<>();
    private ArrayList<CollectInfoChangeBo> collectInfoChangeBos2 = new ArrayList<>();
    private ArrayList<String> postIds = new ArrayList<>();
    private CollectInfoChangeApi collectInfoChangeApi;
    private PostListApi postListApi;
    private int pageNumber = 0; //分页页码
    private boolean isRepeat = false;
    private ArrayList<PostDo> temp;
    private UpdateCollectIsRead updateCollectIsRead;
    private PostNewsAdapter postNewsAdapter;
    private CollectInfoChangeBo collectInfoChangeBo;
    private int positionClick;


    @Override
    protected int setLayoutId() {
        return R.layout.layout_m_recyclerview;
    }

    @Override
    protected void findViews(View view) {
        mRecyclerView = (MRecyclerView) view.findViewById(R.id.mRecyclerView);
    }

    @Override
    protected void initView() {
        mRecyclerView.setIRecycleViewListener(new IRecycleViewListener() {
            @Override
            public void downRefresh() {
                collectInfoChangeApi.startRequest();
            }

            @Override
            public void upRefresh() {
                if (temp.size() == 10) {
                    pageNumber = collectInfoChangeBos2.size() / 10;
                    requestPostList();
                } else {
                    mRecyclerView.stopRefresh(false);
                }
            }

            @Override
            public void onItemClick(int position) {
                CollectInfoBo collectInfoBo = collectInfoChangeBos2.get(position).getCollectInfoBo();
                collectInfoChangeBo = collectInfoChangeBos2.get(position);
                positionClick = position;
                markIsRead();
                if ("pricechange".equalsIgnoreCase(collectInfoChangeBos2.get(position).getChangeType())) {
                    if (collectInfoBo != null) {
                        if ("ershoufang".equalsIgnoreCase(collectInfoBo.getSource())) {
                            startActivity(new Intent(getActivity(), SaleDetailActivity.class)
                                    .putExtra(ExtraConstant.PostId, collectInfoBo.getCollectValue()));
                        } else if ("zufang".equalsIgnoreCase(collectInfoBo.getSource())) {
                            startActivity(new Intent(getActivity(), RentDetailActivity.class)
                                    .putExtra(ExtraConstant.PostId, collectInfoBo.getCollectValue()));
                        }
                    }
                }
            }
        });
        postNewsAdapter = new PostNewsAdapter(getActivity(), collectInfoChangeBos2);
        mRecyclerView.setAdapter(postNewsAdapter);


        collectInfoChangeApi = new CollectInfoChangeApi(PostNewsFragment.class, CollectInfoChangeRo.class, new
                IResponseListener<CollectInfoChangeRo>() {
                    @Override
                    public void onResponse(CollectInfoChangeRo collectInfoChangeRo) {
                        ArrayList<CollectInfoChangeBo> temp = collectInfoChangeRo.getCollectInfoChangeBos();
                        pageNumber = 0;
                        collectInfoChangeBos.clear();
                        collectInfoChangeBos2.clear();
                        postIds.clear();
                        isRepeat = false;
                        if (temp == null || temp.size() == 0) {
                            mRecyclerView.stopRefresh(false);
                            snack(collectInfoChangeRo.getMessage());
                        } else {
                            for (CollectInfoChangeBo collectInfoChangeBo : temp) {
                                if (!"estcount".equalsIgnoreCase(collectInfoChangeBo.getChangeType())) {
                                    if (postIds.size() > 0) {
                                        for (String postId : postIds) {
                                            if (collectInfoChangeBo.getCollectInfoBo().getCollectValue().equals
                                                    (postId)) {
                                                isRepeat = true;
                                            }
                                        }
                                        if (!isRepeat) {
                                            collectInfoChangeBos.add(collectInfoChangeBo);
                                            postIds.add(collectInfoChangeBo.getCollectInfoBo().getCollectValue());
                                        } else {
                                            isRepeat = false;
                                        }
                                    } else {
                                        collectInfoChangeBos.add(collectInfoChangeBo);
                                        postIds.add(collectInfoChangeBo.getCollectInfoBo().getCollectValue());
                                    }
                                }
                            }
                            requestPostList();
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRecyclerView.refreshError();
                    }
                });
        postListApi = new PostListApi(PostNewsFragment.class, PostListRo.class, new IResponseListener<PostListRo>() {
            @Override
            public void onResponse(PostListRo postListRo) {
                temp = postListRo.getList();
                if (temp == null) {
                    mRecyclerView.stopRefresh(false);
                } else {
                    for (PostDo postDo : temp) {
                        collectInfoChangeBos.get(postIds.indexOf(postDo.getPostId())).setPostDo(postDo);
                    }
                    int maxSize = (pageNumber + 1) * 10 > collectInfoChangeBos.size() ? collectInfoChangeBos.size() :
                            (pageNumber + 1) * 10;
                    collectInfoChangeBos2.addAll(collectInfoChangeBos.subList(pageNumber * 10, maxSize));
                    Iterator<CollectInfoChangeBo> colIter = collectInfoChangeBos2.iterator();
                    while (colIter.hasNext()) {
                        CollectInfoChangeBo collectInfoChangeBo = colIter.next();
                        if (collectInfoChangeBo.getPostDo() == null)
                            colIter.remove();
                    }
                    mRecyclerView.stopRefresh(true);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                mRecyclerView.refreshError();
            }
        });
    }

    /**
     * 请求房源列表
     */
    private void requestPostList() {
        StringBuilder ids = new StringBuilder();
        int maxSize = (pageNumber + 1) * 10;
        for (int i = pageNumber * 10; i < postIds.size() && i < maxSize; i++) {
            ids.append(postIds.get(i)).append(",");
        }
        if (TextUtils.isEmpty(ids)) {
            mRecyclerView.stopRefresh(false);
        } else {
            if (ids.toString().contains(",")) {
                ids.deleteCharAt(ids.length() - 1);
                postListApi.setPostIds(ids.toString());
                postListApi.startRequest();
            }
        }
    }

    private void markIsRead() {
        if (updateCollectIsRead == null)
            updateCollectIsRead = new UpdateCollectIsRead(PostNewsFragment.class, SimpleUserCenterRo.class, new IResponseListener<SimpleUserCenterRo>() {
                @Override
                public void onResponse(SimpleUserCenterRo simpleUserCenterRo) {
                    collectInfoChangeBo.setRead(true);
                    mRecyclerView.notifyItemChanged(positionClick);
                }

                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
        updateCollectIsRead.setCollectID(collectInfoChangeBo.getCollectID());
        updateCollectIsRead.startRequest();
    }

    @Override
    protected void loadData() {
        if (!isRequest) {
            isRequest = true;
            mRecyclerView.startRefresh();
        }
    }

}
